<template>
  <div class="video-player-modal" v-if="show" @click="closeModal">
    <div class="video-player-container" @click.stop>
      <!-- 播放器头部 -->
      <div class="video-player-header">
        <div class="video-info">
          <h3 class="video-title">{{ videoInfo.title || '视频播放' }}</h3>
          <p class="video-meta">
            {{ videoInfo.duration }} • {{ videoInfo.fileSize }}
            <span v-if="videoInfo.filePath" class="ml-2 text-blue-400">
              • {{ getFileFormatDisplay(videoInfo.filePath) }}
            </span>
          </p>
          <div v-if="currentAbsoluteTime" class="current-time-info">
            <i class="fa-solid fa-clock mr-1"></i>
            <span class="text-sm text-gray-300">
              当前时间: {{ formatDateTime(currentAbsoluteTime) }}
            </span>
          </div>
        </div>
        <button @click="closeModal" class="close-button">
          <i class="fa-solid fa-times"></i>
        </button>
      </div>
      
      <!-- 视频播放区域 -->
      <div class="video-container">
        <video 
          ref="videoPlayer"
          :src="videoUrl"
          @loadedmetadata="onVideoLoaded"
          @timeupdate="onTimeUpdate"
          @ended="onVideoEnded"
          @error="onVideoError"
          @play="onPlay"
          @pause="onPause"
          class="video-element">
          您的浏览器不支持视频播放
        </video>
        
        <!-- 加载状态 -->
        <div v-if="isLoading" class="loading-overlay">
          <div class="loading-spinner">
            <i class="fa-solid fa-spinner fa-spin text-6xl text-blue-400 mb-4"></i>
            <p class="loading-text text-xl font-semibold">视频加载中...</p>
            <p class="loading-subtitle text-sm text-gray-300 mt-2">请稍候，正在准备播放内容</p>
            <div class="loading-progress mt-4">
              <div class="progress-bar bg-gray-600 rounded-full h-2 w-48 mx-auto">
                <div class="progress-fill bg-blue-400 h-2 rounded-full animate-pulse"></div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 错误状态 -->
        <div v-if="hasError" class="error-overlay">
          <div class="error-content">
            <i class="fa-solid fa-exclamation-triangle text-6xl text-red-400 mb-4"></i>
            <p class="error-title">视频加载失败</p>
            <p class="error-message">{{ errorMessage }}</p>
            <div class="debug-info mt-4 p-3 bg-gray-800 rounded text-sm text-gray-300">
              <p><strong>视频URL:</strong> {{ videoUrl }}</p>
              <p><strong>文件路径:</strong> {{ videoInfo.filePath || 'N/A' }}</p>
            </div>
            <button @click="retryLoad" class="retry-button">
              <i class="fa-solid fa-refresh mr-2"></i> 重试
            </button>
          </div>
        </div>
        
        <!-- 播放控制栏 -->
        <div class="video-controls" :class="{ 'controls-hidden': !showControls }">
          <!-- 进度条 -->
          <div class="progress-container">
            <div class="progress-bar" @click="seekTo">
              <div class="progress-filled" :style="{ width: progressPercent + '%' }"></div>
              <div class="progress-handle" :style="{ left: progressPercent + '%' }"></div>
            </div>
          </div>
          
          <!-- 控制按钮 -->
          <div class="controls-row">
            <div class="controls-left">
              <button @click="togglePlayPause" class="control-button">
                <i :class="isPlaying ? 'fa-solid fa-pause' : 'fa-solid fa-play'"></i>
              </button>
              
              <div class="time-display">
                <div class="time-info">
                  <span class="current-time">{{ formatTime(currentTime) }}</span>
                  <span class="time-separator">/</span>
                  <span class="total-time">{{ formatTime(duration) }}</span>
                </div>
                <div class="time-progress">
                  <span class="progress-percent">{{ Math.round(progressPercent) }}%</span>
                </div>
              </div>
              
              <button @click="toggleMute" class="control-button">
                <i :class="isMuted ? 'fa-solid fa-volume-mute' : 'fa-solid fa-volume-up'"></i>
              </button>
              
              <div class="volume-container">
                <input 
                  type="range" 
                  min="0" 
                  max="1" 
                  step="0.1" 
                  v-model="volume"
                  @input="onVolumeChange"
                  class="volume-slider">
              </div>
            </div>
            
            <div class="controls-right">
              <button @click="toggleFullscreen" class="control-button">
                <i :class="isFullscreen ? 'fa-solid fa-compress' : 'fa-solid fa-expand'"></i>
              </button>
              
              <button @click="downloadVideo" class="control-button">
                <i class="fa-solid fa-download"></i>
              </button>
            </div>
          </div>
        </div>
        
        <!-- 等待加载状态 -->
        <div v-if="!isPlaying && !isLoading && !hasError && isWaitingForLoad" class="waiting-overlay">
          <div class="waiting-content">
            <i class="fa-solid fa-clock text-6xl text-yellow-400 mb-4"></i>
            <p class="waiting-text text-xl font-semibold">等待视频加载...</p>
            <p class="waiting-subtitle text-sm text-gray-300 mt-2">视频尚未加载完成，请稍候</p>
            <div class="waiting-dots mt-4">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
          </div>
        </div>
        
        <!-- 播放/暂停按钮（中央） -->
        <div v-if="!isPlaying && !isLoading && !hasError && !isWaitingForLoad" class="play-button-overlay" @click="play">
          <div class="play-button">
            <i class="fa-solid fa-play text-6xl"></i>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  videoUrl: {
    type: String,
    required: true
  },
  videoInfo: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['close'])

// 响应式数据
const videoPlayer = ref(null)
const isLoading = ref(false)
const hasError = ref(false)
const errorMessage = ref('')
const isPlaying = ref(false)
const isMuted = ref(false)
const isFullscreen = ref(false)
const showControls = ref(true)
const isWaitingForLoad = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const volume = ref(1)
const controlsTimer = ref(null)

// 计算属性
const progressPercent = computed(() => {
  if (duration.value === 0) return 0
  return (currentTime.value / duration.value) * 100
})

// 计算当前播放的绝对时间（基于录制开始时间）
const currentAbsoluteTime = computed(() => {
  if (!props.videoInfo.startTime || !currentTime.value) return null
  
  try {
    const startTime = new Date(props.videoInfo.startTime)
    const currentTimeMs = currentTime.value * 1000 // 转换为毫秒
    const absoluteTime = new Date(startTime.getTime() + currentTimeMs)
    return absoluteTime
  } catch (error) {
    console.error('计算绝对时间失败:', error)
    return null
  }
})

// 方法
const closeModal = () => {
  emit('close')
}

const onVideoLoaded = () => {
  isLoading.value = false
  hasError.value = false
  if (videoPlayer.value && !isNaN(videoPlayer.value.duration)) {
    duration.value = videoPlayer.value.duration
  }
  if (videoPlayer.value) {
    videoPlayer.value.volume = volume.value
  }
}

const onTimeUpdate = () => {
  if (videoPlayer.value && !isNaN(videoPlayer.value.currentTime)) {
    currentTime.value = videoPlayer.value.currentTime
  }
}

const onVideoEnded = () => {
  isPlaying.value = false
  currentTime.value = 0
}

const onVideoError = (event) => {
  isLoading.value = false
  hasError.value = true
  errorMessage.value = '视频加载失败，请检查网络连接或文件是否存在'
  console.error('视频播放错误:', event)
}

const onPlay = () => {
  isPlaying.value = true
}

const onPause = () => {
  isPlaying.value = false
}

const play = async () => {
  if (!videoPlayer.value) {
    console.warn('视频元素不存在，无法播放')
    return
  }
  
  try {
    // 确保视频已加载
    if (videoPlayer.value.readyState < 2) {
      console.log('视频尚未加载完成，等待加载...')
      isWaitingForLoad.value = true
      isLoading.value = false
      
      // 监听视频加载完成事件
      const onCanPlay = () => {
        isWaitingForLoad.value = false
        isLoading.value = false
        videoPlayer.value.removeEventListener('canplay', onCanPlay)
        // 自动播放
        videoPlayer.value.play()
      }
      
      videoPlayer.value.addEventListener('canplay', onCanPlay)
      return
    }
    
    isWaitingForLoad.value = false
    await videoPlayer.value.play()
  } catch (error) {
    console.error('视频播放失败:', error)
    isWaitingForLoad.value = false
    // 如果是被中断的错误，可以忽略
    if (error.name !== 'AbortError' && error.name !== 'NotAllowedError') {
      hasError.value = true
      errorMessage.value = '视频播放失败，请重试'
    }
  }
}

const togglePlayPause = async () => {
  if (!videoPlayer.value) {
    console.warn('视频元素不存在，无法切换播放状态')
    return
  }
  
  try {
    if (isPlaying.value) {
      videoPlayer.value.pause()
    } else {
      await play()
    }
  } catch (error) {
    console.error('切换播放状态失败:', error)
  }
}

const toggleMute = () => {
  if (videoPlayer.value) {
    videoPlayer.value.muted = !videoPlayer.value.muted
    isMuted.value = videoPlayer.value.muted
  }
}

const onVolumeChange = () => {
  if (videoPlayer.value) {
    videoPlayer.value.volume = volume.value
    isMuted.value = volume.value === 0
  }
}

const seekTo = (event) => {
  if (videoPlayer.value && duration.value > 0) {
    const rect = event.currentTarget.getBoundingClientRect()
    const clickX = event.clientX - rect.left
    const percentage = clickX / rect.width
    const newTime = percentage * duration.value
    videoPlayer.value.currentTime = newTime
  }
}

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    // 进入全屏
    if (videoPlayer.value.requestFullscreen) {
      videoPlayer.value.requestFullscreen()
    } else if (videoPlayer.value.webkitRequestFullscreen) {
      videoPlayer.value.webkitRequestFullscreen()
    } else if (videoPlayer.value.msRequestFullscreen) {
      videoPlayer.value.msRequestFullscreen()
    }
  } else {
    // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    }
  }
}

const downloadVideo = () => {
  const link = document.createElement('a')
  link.href = props.videoUrl
  link.download = props.videoInfo.title || 'video.mp4.tmp'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const retryLoad = () => {
  hasError.value = false
  isLoading.value = true
  isPlaying.value = false
  
  if (videoPlayer.value) {
    // 先暂停，然后重新加载
    videoPlayer.value.pause()
    setTimeout(() => {
      if (videoPlayer.value) {
        videoPlayer.value.load()
      }
    }, 100)
  }
}

const formatTime = (time) => {
  if (!time || isNaN(time)) return '00:00'
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取文件格式显示名称
const getFileFormatDisplay = (filePath) => {
  if (!filePath) return '未知格式'
  if (filePath.endsWith('.mp4.tmp')) return 'MP4 (临时)'
  if (filePath.endsWith('.mp4')) return 'MP4'
  if (filePath.endsWith('.flv')) return 'FLV'
  if (filePath.endsWith('.avi')) return 'AVI'
  if (filePath.endsWith('.mov')) return 'MOV'
  return '视频文件'
}

const showControlsTemporarily = () => {
  showControls.value = true
  if (controlsTimer.value) {
    clearTimeout(controlsTimer.value)
  }
  controlsTimer.value = setTimeout(() => {
    if (isPlaying.value) {
      showControls.value = false
    }
  }, 3000)
}

const hideControls = () => {
  if (isPlaying.value) {
    showControls.value = false
  }
}

// 监听全屏状态变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

// 键盘事件处理
const handleKeydown = (event) => {
  if (!props.show) return
  
  switch (event.key) {
    case ' ':
      event.preventDefault()
      togglePlayPause()
      break
    case 'Escape':
      if (isFullscreen.value) {
        toggleFullscreen()
      } else {
        closeModal()
      }
      break
    case 'f':
    case 'F':
      toggleFullscreen()
      break
    case 'm':
    case 'M':
      toggleMute()
      break
    case 'ArrowLeft':
      event.preventDefault()
      if (videoPlayer.value) {
        videoPlayer.value.currentTime = Math.max(0, videoPlayer.value.currentTime - 10)
      }
      break
    case 'ArrowRight':
      event.preventDefault()
      if (videoPlayer.value) {
        videoPlayer.value.currentTime = Math.min(duration.value, videoPlayer.value.currentTime + 10)
      }
      break
  }
}

// 监听视频URL变化
watch(() => props.videoUrl, (newUrl) => {
  if (newUrl && videoPlayer.value) {
    // 注释：检查URL是否为临时文件，如果是则显示提示
    // if (newUrl.includes('.mp4.tmp')) {
    //   console.log('检测到临时文件，等待录制完成:', newUrl);
    //   hasError.value = true;
    //   errorMessage.value = '文件仍在录制中，请等待录制完成后再播放';
    //   return;
    // }
    
    console.log('视频URL变化，开始加载新视频:', newUrl)
    isLoading.value = true
    hasError.value = false
    isPlaying.value = false
    isWaitingForLoad.value = false
    
    // 先暂停当前播放，然后加载新视频
    try {
      if (!videoPlayer.value.paused) {
        videoPlayer.value.pause()
      }
    } catch (error) {
      console.warn('暂停视频时出错:', error)
    }
    
    // 使用setTimeout确保暂停操作完成后再加载
    setTimeout(() => {
      if (videoPlayer.value) {
        try {
          videoPlayer.value.load()
        } catch (error) {
          console.error('加载视频失败:', error)
          hasError.value = true
          errorMessage.value = '视频加载失败'
        }
      }
    }, 100)
  }
})

// 监听显示状态
watch(() => props.show, (show) => {
  if (show) {
    showControls.value = true
  } else {
    // 暂停播放
    if (videoPlayer.value) {
      videoPlayer.value.pause()
    }
  }
})

onMounted(() => {
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('mozfullscreenchange', handleFullscreenChange)
  document.addEventListener('MSFullscreenChange', handleFullscreenChange)
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange)
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange)
  document.removeEventListener('keydown', handleKeydown)
  
  if (controlsTimer.value) {
    clearTimeout(controlsTimer.value)
  }
})
</script>

<style scoped>
.video-player-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.9);
  z-index: 10000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player-container {
  width: 90%;
  max-width: 1200px;
  background: #000;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5);
}

.video-player-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: linear-gradient(135deg, #1f2937 0%, #374151 100%);
  color: white;
}

.video-title {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0;
}

.video-meta {
  font-size: 0.875rem;
  color: #9ca3af;
  margin: 4px 0 0 0;
}

.close-button {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.close-button:hover {
  background: rgba(255, 255, 255, 0.1);
}

.video-container {
  position: relative;
  width: 100%;
  aspect-ratio: 16/9;
  background: #000;
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.loading-overlay,
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  text-align: center;
  color: white;
}

.loading-text {
  margin-top: 16px;
  font-size: 1.125rem;
}

.error-content {
  text-align: center;
  color: white;
}

.error-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 16px 0 8px 0;
}

.error-message {
  color: #9ca3af;
  margin-bottom: 24px;
}

.retry-button {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.retry-button:hover {
  background: #2563eb;
}

.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 16px 24px 24px;
  transition: opacity 0.3s ease;
}

.controls-hidden {
  opacity: 0;
  pointer-events: none;
}

.progress-container {
  margin-bottom: 16px;
}

.progress-bar {
  position: relative;
  height: 6px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  cursor: pointer;
}

.progress-filled {
  height: 100%;
  background: #3b82f6;
  border-radius: 3px;
  transition: width 0.1s ease;
}

.progress-handle {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 16px;
  height: 16px;
  background: #3b82f6;
  border-radius: 50%;
  border: 2px solid white;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.progress-bar:hover .progress-handle {
  opacity: 1;
}

.controls-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.controls-left,
.controls-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.control-button {
  background: none;
  border: none;
  color: white;
  font-size: 1.25rem;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.control-button:hover {
  background: rgba(255, 255, 255, 0.1);
}

.time-display {
  color: white;
  font-size: 0.875rem;
  font-family: monospace;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-info {
  display: flex;
  align-items: center;
}

.time-separator {
  margin: 0 4px;
  color: #9ca3af;
}

.time-progress {
  font-size: 0.75rem;
  color: #9ca3af;
  text-align: center;
}

.current-time-info {
  margin-top: 4px;
  display: flex;
  align-items: center;
  font-size: 0.75rem;
}

.volume-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.volume-slider {
  width: 80px;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  outline: none;
  cursor: pointer;
}

.volume-slider::-webkit-slider-thumb {
  appearance: none;
  width: 16px;
  height: 16px;
  background: #3b82f6;
  border-radius: 50%;
  cursor: pointer;
}

.volume-slider::-moz-range-thumb {
  width: 16px;
  height: 16px;
  background: #3b82f6;
  border-radius: 50%;
  cursor: pointer;
  border: none;
}

.play-button-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  cursor: pointer;
}

.play-button {
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1f2937;
  transition: all 0.3s ease;
}

.play-button:hover {
  background: white;
  transform: scale(1.1);
}

.waiting-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.waiting-content {
  text-align: center;
  color: white;
}

.waiting-text {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 16px 0 8px 0;
}

.waiting-subtitle {
  color: #9ca3af;
  margin-bottom: 24px;
}

.waiting-dots {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.dot {
  width: 12px;
  height: 12px;
  background: #fbbf24;
  border-radius: 50%;
  animation: waiting-bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

.dot:nth-child(3) {
  animation-delay: 0s;
}

@keyframes waiting-bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-player-container {
    width: 95%;
  }
  
  .video-player-header {
    padding: 12px 16px;
  }
  
  .video-title {
    font-size: 1.125rem;
  }
  
  .video-meta {
    font-size: 0.75rem;
  }
  
  .video-controls {
    padding: 12px 16px 16px;
  }
  
  .controls-left,
  .controls-right {
    gap: 12px;
  }
  
  .volume-container {
    display: none;
  }
}
</style>

